<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Login extends Base_Controller{
	
	public function __construct(){
		parent::__construct();
		$this->load->model('admin_model');
		$this->load->library('session');
	}
	
	public function index(){
		if($this->session->userdata('admin')){
			redirect($this->_url['home'].'/');
		}
		$assign = [
			'username' => $this->input->cookie('adm_username'),
			'refer' => $this->input->get('refer')
		];
		$this->ci_smarty->assign($assign);
		$this->ci_smarty->display('login.htm');
	}
	
	public function quit(){
		$this->clear_login();
		$redirect = $this->_url['home'].'/login/';
		if($_SERVER['HTTP_REFERER']){
			$redirect .= '?refer='.urlencode($_SERVER['HTTP_REFERER']);
		}
		redirect($redirect);
	}
	
	public function submit(){
		$this->load->library('form_validation');
		$this->form_validation->set_rules('username', '用户名', 'required');
		$this->form_validation->set_rules('password', '密码', 'required');
		$this->form_validation->set_rules('capcode', '验证码', 'required');
		if($this->form_validation->run() == false){
			foreach($this->form_validation->error_array() as $filed => $error){
				$this->output_json([
					'retcode' => -1,
					'message' => $error
				]);
			}
		}
		$posts = $this->input->post();
		if($this->session->capcode != strtolower($posts['capcode'])){
			$this->output_json('验证码不正确');
		}
		$login = $this->admin_model->login($posts);
		if($login){
			$this->save_login($login);
			$this->output_json([
				'message' => '登录成功',
				'redirect' => $posts['refer']
			], 0);
		}
		$this->output_json('用户名或密码错误');
	}
	
	// 保存登录信息
	private function save_login($data){
		$this->session->set_userdata('admin', $data);
		$this->input->set_cookie('adm_username', $data['username'], 3600 * 24 * 30);
	}
	
	// 清除登录信息
	private function clear_login(){
		$this->session->unset_userdata('admin');
	}
	
}